<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="8">
                <el-card class="box-card">
                    <div slot="header" class="clearfix col-title-box">
                        <div class="col-title">第一步 案件基本信息 [保存时间: {{ caseTime }}]</div>
                        <el-divider direction="vertical"></el-divider>
                        <el-button v-if="showFirstContent" size="mini" type="text"
                            @click="showFirstContent = !showFirstContent">收起</el-button>
                        <el-button v-else size="mini" type="text"
                            @click="showFirstContent = !showFirstContent">展开</el-button>
                    </div>
                    <el-form v-if="showFirstContent" :model="firstForm" :rules="firstRules" ref="firstForm"
                        label-width="120px">
                        <el-form-item label="所属机构" prop="deptId">
                            <el-select v-model="firstForm.deptId" placeholder="请选择所属机构" style="width: 100%;"
                                @change="loadUsers()">
                                <el-option v-for="(item, index) in deptOptions" :key="index" :label="item.deptName"
                                    :value="item.deptId"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="调解员" prop="mediatorId">
                            <el-select v-model="firstForm.mediatorId" placeholder="请选择调解员" style="width: 100%;">
                                <el-option v-for="(item, index) in userOptions" :key="index" :label="item.nickName"
                                    :value="item.userId"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="案号" prop="caseNumber">
                            <el-input v-model="firstForm.caseNumber" placeholder="请输入案号"></el-input>
                        </el-form-item>
                        <el-form-item label="案由" prop="reason">
                            <el-input v-model="firstForm.reason" placeholder="请输入案由"></el-input>
                        </el-form-item>
                        <el-form-item label="标的额" prop="caseAmount">
                            <el-input v-model="firstForm.caseAmount" placeholder="请输入标的额">
                                <template slot="append">元</template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="接收日期" prop="startDate">
                            <el-date-picker v-model="firstForm.startDate" type="date" value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd" placeholder="请选择接收日期" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="调解截止日期" prop="endDate">
                            <el-date-picker v-model="firstForm.endDate" type="date" value-format="yyyy-MM-dd"
                                format="yyyy-MM-dd" placeholder="请选择调解截止日期" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                        <el-form-item label="外部编号" prop="outNumber">
                            <el-input v-model="firstForm.outNumber" placeholder="请输入外部编号"></el-input>
                        </el-form-item>
                        <el-form-item label="纠纷发生地址" prop="caseAddress">
                            <el-input v-model="firstForm.caseAddress" placeholder="请输入纠纷发生地址"></el-input>
                        </el-form-item>

                        <el-form-item label="事实与理由" prop="reasonDetail">
                            <el-input type="textarea" v-model="firstForm.reasonDetail"
                                placeholder="请输入事实与理由"></el-input>
                        </el-form-item>
                        <el-form-item label="诉求" prop="demands">
                            <el-input type="textarea" v-model="firstForm.demands" placeholder="请输入诉求"></el-input>
                        </el-form-item>
                        <el-form-item label="备注" prop="note">
                            <el-input type="textarea" v-model="firstForm.note" placeholder="请输入备注"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" :disabled="caseId != ''" @click="addCase()">保存</el-button>

                        </el-form-item>
                    </el-form>
                </el-card>
            </el-col>
            <el-col :span="8">

                <el-card class="box-card">
                    <div slot="header" class="clearfix col-title-box">
                        <div class="col-title">第二步 当事人信息 [现录入 {{ plaintiffNum }} 个原告 {{ defendantNum }} 个被告 ]</div>
                        <el-divider direction="vertical" />
                        <el-button type="success" icon="el-icon-push" style="padding: 3px;" size="mini"
                            @click="addSecondData()">新增当事人</el-button>
                        <el-button v-if="showSecondContent" @click="showSecondContent = !showSecondContent" type="text"
                            size="mini">收起</el-button>
                        <el-button v-else @click="showSecondContent = !showSecondContent" type="text"
                            size="mini">展开</el-button>
                    </div>
                    <el-table v-if="showSecondContent" :data="secondData" style="width: 100%">
                        <el-table-column prop="caseUserRole" label="角色">
                            <template slot-scope="scope">
                                <span>{{ caseRoleTypeMap[scope.row.caseUserRole] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="userName" label="姓名">
                        </el-table-column>
                        <el-table-column prop="userType" label="类型">
                            <template slot-scope="scope">
                                <span>{{ caseUserTypeMap[scope.row.userType] }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="contactPhone" label="电话">
                        </el-table-column>
                        <el-table-column prop="address" label="地址">
                        </el-table-column>
                        <el-table-column prop="idNumber" label="机构代码/身份证">
                        </el-table-column>
                        <el-table-column label="操作" width="80px">
                            <template slot-scope="scope">
                                <el-popconfirm confirm-button-text='删除' cancel-button-text='点错了'
                                    @confirm="deleCaseUserItem(scope.row)" icon="el-icon-info" icon-color="red"
                                    title="您确定删除本条当事人信息吗？">
                                    <el-button type="danger" icon="el-icon-delete" slot="reference"
                                        size="mini">删除</el-button>
                                </el-popconfirm>

                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="box-card">
                    <div slot="header" class="clearfix col-title-box">
                        <div class="col-title">第三步 案件证据材料 [已上传 0 个]</div>
                        <el-divider direction="vertical" />
                        <el-button type="success" icon="el-icon-push" style="padding: 3px;" size="mini"
                            @click="addFile()">新增文件</el-button>
                        <el-button v-if="showThirdContent" size="mini" type="text"
                            @click="showThirdContent = !showThirdContent">收起</el-button>
                        <el-button v-else size="mini" type="text"
                            @click="showThirdContent = !showThirdContent">展开</el-button>
                    </div>
                    <el-table v-if="showThirdContent" :data="caseFileList" style="width: 100%">
                        <el-table-column prop="fileName" label="材料名称">
                        </el-table-column>
                        <el-table-column prop="filePath" label="文件地址">
                        </el-table-column>
                        <el-table-column prop="name" label="操作" width="80px">
                            <template slot-scope="scope">
                                <el-popconfirm confirm-button-text='删除' cancel-button-text='点错了' icon="el-icon-info"
                                    @confirm="deleFileItem(scope.row)" icon-color="red" title="你确定删除该文件吗？">
                                    <el-button type="danger" slot="reference" icon="el-icon-delete"
                                        size="mini">删除</el-button>
                                </el-popconfirm>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog title="添加当事人" :visible.sync="secondVisible" width="30%" :before-close="secondClose">

            <el-form :model="secondForm" :rules="secondRules" ref="secondForm" label-width="120px">
                <el-form-item label="角色" prop="caseUserRole">
                    <el-select v-model="secondForm.caseUserRole" placeholder="请选择角色" style="width: 100%;">
                        <el-option v-for="dict in dict.type.case_role_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="类型" prop="userType">
                    <el-select v-model="secondForm.userType" placeholder="请选择类型" style="width: 100%;">
                        <el-option v-for="dict in dict.type.case_user_type" :key="dict.value" :label="dict.label"
                            :value="dict.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="secondForm.userType == '02'" label="姓名" prop="userName">
                    <el-input v-model="secondForm.userName" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item v-else label="组织机构名称" prop="userName">
                    <el-input v-model="secondForm.userName" placeholder="请输入组织机构名称"></el-input>
                </el-form-item>

                <el-form-item v-if="secondForm.userType != '02'" label="联系人" prop="contactName">
                    <el-input v-model="secondForm.contactName" placeholder="请输入联系人"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="contactPhone">
                    <el-input v-model="secondForm.contactPhone" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="secondForm.address" placeholder="请输入地址"></el-input>
                </el-form-item>
                <el-form-item v-if="secondForm.userType == '02'" label="身份证号" prop="idNumber">
                    <el-input v-model="secondForm.idNumber" placeholder="请输入身份证号"></el-input>
                </el-form-item>
                <el-form-item v-else label="组织机构代码" prop="idNumber">
                    <el-input v-model="secondForm.idNumber" placeholder="请输入组织机构代码"></el-input>
                </el-form-item>

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="secondCancel()">取 消</el-button>
                <el-button type="primary" @click="secondSave()">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog title="添加文件" :visible.sync="thirdVisible" width="400px" :before-close="thirdClose">
            <el-form :model="fileForm" label-width="80px">
                <el-form-item label="文件名称" prop="userName">
                    <el-input v-model="fileForm.fileName" placeholder="请输入文件名称">
                        <template slot="append">{{ suffix }}</template>
                    </el-input>
                </el-form-item>
            </el-form>

            <el-upload class="upload-demo" drag action="#" :multiple="false" :file-list="fileList"
                :http-request="requestUpload" :before-upload="beforeUpload">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
            <span slot="footer" class="dialog-footer">
                <el-button @click="thirdVisible = false">取 消</el-button>
                <el-button type="primary" @click="unloadFile()">上传文件</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { listDept } from "@/api/system/dept"
import { listUser } from "@/api/system/user"
import { addCaseInfo } from "@/api/case/info"
import { addCaseUser, listCaseUser, delCaseUser } from "@/api/case/user"
import { addCaseFile, listCaseFile, delCaseFile } from "@/api/case/file"

export default {
    name: '',
    dicts: ['case_role_type', 'case_user_type', 'case_stage', 'case_stage_flag'],
    data() {
        return {
            jgPid: process.env.VUE_APP_JG_PID,
            deptOptions: [],
            userOptions: [],
            showFirstContent: true,
            caseId: '',
            caseTime: 'never',
            firstForm: {
                deptId: '',
                mediatorId: '',
                caseNumber: '',
                reason: '',
                caseAmount: '',
                startDate: '',
                endDate: '',
                caseAddress: '',
                reasonDetail: '',
                outNumber: '',
                demands: '',
                note: '',
                caseStage: '',
                flag: 1
            },
            firstRules: {
                deptId: [{ required: true, message: '请选择所属机构', trigger: 'change' }],
                caseNumber: [{ required: true, message: '请输入案号', trigger: 'blur' }],
                reason: [{ required: true, message: '请输入案由', trigger: 'blur' }],
                caseAmount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
                startDate: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
                endDate: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
            },
            showSecondContent: true,
            secondData: [],
            secondForm: {
                caseId: '',
                caseUserRole: '',
                userName: '',
                userType: '',
                contactPhone: '',
                address: '',
                idNumber: '',

            },
            secondRules: {
                caseUserRole: [{ required: true, message: '请选择角色', trigger: 'blur' }],
                userName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                userType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
            },
            caseRoleTypeMap: {},
            caseUserTypeMap: {},
            plaintiffNum: 0,
            defendantNum: 0,
            showThirdContent: true,
            secondVisible: false,
            thirdVisible: false,
            caseFileList: [],
            fileList: [],
            file: null,
            suffix: '',
            fileForm: {
                fileName: ''
            }
        }
    },
    created() {
        this.loadDepts()
        this.initDate()
    },
    methods: {
        initMap() {
            let map = {}
            let map2 = {}
            for (let i = 0; i < this.dict.type.case_role_type.length; i++) {
                const dict = this.dict.type.case_role_type[i];
                map[dict.value] = dict.label
            }
            for (let i = 0; i < this.dict.type.case_user_type.length; i++) {
                const dict = this.dict.type.case_user_type[i];
                map2[dict.value] = dict.label
            }

            this.caseRoleTypeMap = map
            this.caseUserTypeMap = map2
        },
        initDate() {
            const date = new Date()
            this.firstForm.startDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
            date.setMonth(date.getMonth() + 1)
            date.setDate(date.getDate() + 1)
            this.firstForm.endDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
        },
        loadDepts() {
            listDept().then(res => {
                this.deptOptions = res.data.filter(item => item.parentId == this.jgPid)
                console.log(this.deptOptions);
            })
        },
        loadUsers() {
            listUser({
                pageNum: 1,
                pageSize: 9999,
                deptId: this.firstForm.deptId,
                roleId: process.env.VUE_APP_TJ_ROLE_ID
            }).then(res => {
                this.userOptions = res.rows
            })
        },
        addSecondData() {
            if (this.caseId == '') {
                this.$message({
                    message: '请先输入案件基本信息并保存',
                    type: 'error'
                })
                return
            }
            this.secondForm.caseId = this.caseId
            this.secondVisible = true
        },
        initSecondData() {
            this.secondForm = {
                caseId: this.caseId,
                caseUserRole: '',
                userName: '',
                userType: '',
                contactPhone: '',
                address: '',
                idNumber: '',
            }
        },
        addCase() {
            this.$refs.firstForm.validate((valid) => {
                if (valid) {
                    this.firstForm.caseStage = this.dict.type.case_stage[0].value
                    this.firstForm.flag = this.dict.type.case_stage_flag[0].value
                    addCaseInfo(this.firstForm).then(res => {
                        this.caseId = res.data.id
                        this.caseTime = res.data.createTime
                    })
                }
            })
        },
        secondClose(done) {
            this.initSecondData()
            this.$refs.secondForm.resetFields()
            done()
        },
        secondCancel() {
            this.initSecondData()
            this.$refs.secondForm.resetFields()
            this.secondVisible = false
        },
        secondSave() {
            this.$refs.secondForm.validate(valid => {
                if (valid) {
                    addCaseUser(this.secondForm).then(res => {
                        this.secondCancel()
                        this.loadCaseUser()
                    })
                }
            })
        },
        deleCaseUserItem(item) {
            delCaseUser(item.id).then(res => {
                this.$message({
                    message: '当事人删除成功',
                    type: 'success'
                });
                this.loadCaseUser()
            })
        },
        loadCaseUser() {
            listCaseUser({
                caseId: this.caseId
            }).then(res => {
                this.secondData = res.rows
                this.plaintiffNum = 0
                this.defendantNum = 0
                for (let i = 0; i < this.secondData.length; i++) {
                    const user = this.secondData[i];
                    if (user.caseUserRole == '01') {
                        this.plaintiffNum++
                    } else {
                        this.defendantNum++
                    }
                }
                this.initMap()
            })
        },
        addFile() {
            if (this.caseId == '') {
                this.$message({
                    message: '请先输入案件基本信息并保存',
                    type: 'error'
                })
                return
            }
            this.fileList = []
            this.file = null
            this.suffix = ''
            this.fileForm = {
                fileName: ''
            }
            this.thirdVisible = true
        },
        thirdClose(done) {
            done()
        },
        // 覆盖默认的上传行为
        requestUpload(e) {
            // console.log(e);
            this.file = e.file
            let names = this.file.name.split('.')
            this.suffix = `.${names[1]}`
            if (!this.fileForm.fileName) {
                this.fileForm.fileName = names[0]
            }
        },
        beforeUpload(file) {
            this.fileList = [file]
        },
        unloadFile() {
            if (!this.file) {
                this.$message.error('请先上传文件');
                return
            }
            debugger
            let formData = new FormData()
            formData.append('file', this.file)
            formData.append('fileName', `${this.fileForm.fileName}${this.suffix}`)
            formData.append('caseId', this.caseId)

            addCaseFile(formData).then(res => {
                this.$message({
                    message: '文件上传成功',
                    type: 'success'
                });
                this.thirdVisible = false
                this.loadCaseFile()
            })
        },
        // 查询案件文件
        loadCaseFile() {
            listCaseFile({
                caseId: this.caseId
            }).then(res => {
                this.caseFileList = res.rows
            })
        },
        // 删除文件
        deleFileItem(item) {
            delCaseFile(item.id).then(res => {
                this.$message({
                    message: '文件删除成功',
                    type: 'success'
                });
                this.loadCaseFile()
            })
        }

    }

}
</script>

<style scoped>
.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.col-title-box {
    width: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    align-items: center;
}

.col-title {
    width: max-content;
    font-size: 16px;
    font-weight: bold;
    flex: 1;
}

/deep/ .el-card__header {
    background: #F4F4F4 !important;
}
</style>